import ContactDrawer from '@/components/ContactDrawer';
import Footer from '@/components/Footer';
import {
  bindAccountOrganization,
  bindAccountQueryByPhone,
  loginAppForWechatBindAccount,
} from '@/services/api/api-login';
import { isDev } from '@/utils/dev';
import { setToken } from '@/utils/token';
import { MobileOutlined, UserOutlined } from '@ant-design/icons';
import {
  LoginForm,
  ProFormCascader,
  ProFormGroup,
  ProFormList,
  ProFormText,
} from '@ant-design/pro-components';

import { Alert, message } from 'antd';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import React, { useEffect, useState } from 'react';
import { Helmet, history, useLocation, useModel } from 'umi';

export default (): React.ReactNode => {
  const { initialState, setInitialState } = useModel('@@initialState');

  let location = useLocation();

  const parse = (str = window.location.search) => {
    const reg = /([^?&=]+)=([^&]+)/g; // 分组捕获 两个子组
    const params = {};
    str.replace(reg, (_, k, v) => (params[k] = v));
    return params;
  };

  const [bindStep, setBindStepState] = useState<number>(0);

  const [bindState, setBindStateState] = useState<number>(0);
  const [disabledPhone, setDisabledPhoneState] = useState<boolean>(false);

  /**
   * 初始化树形数据
   */
  const [treeOrganizationData, setTreeOrganizationDataState] = useState<DataNode[]>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载单位详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await bindAccountOrganization();
      if (response.code === 0) {
        const treeData = readyTreeData(response.data);
        setTreeOrganizationDataState(treeData);
      }
    } catch (error) {}
  };

  useEffect(() => {
    if (isDev()) {
      return;
    }

    const { wechat } = parse(location.search) as { wechat: string };
    if (wechat === undefined) {
      history.push('/user/login');
      message.warning('跳转到登录界面');
    }
  }, []);

  const helmetMessage = () => {
    if (bindStep === 0) {
      return '查询';
    } else if (bindStep === 1 && bindState === 1) {
      return '绑定';
    } else if (bindStep === 1 && bindState === 0) {
      return '注册';
    }
  };

  const alertContainer = () => {
    if (bindStep === 0) {
      return (
        <Alert
          style={{
            marginBottom: 24,
          }}
          message={'请填写手机号，查询账户状态'}
          type="info"
          showIcon
        />
      );
    } else if (bindStep === 1 && bindState === 0) {
      return (
        <>
          <Alert
            style={{
              marginBottom: 24,
            }}
            message={'填写所有信息，提交后待管理员审核完成注册流程'}
            type="info"
            showIcon
          />
          <Alert
            style={{
              marginBottom: 24,
            }}
            message="如您有多个单位需要关联可与管理员联系进行绑定"
            type="warning"
            showIcon
          />
        </>
      );
    } else if (bindStep === 1 && bindState === 1) {
      return (
        <>
          <Alert
            style={{
              marginBottom: 10,
            }}
            message={'管理员已为您添加好了账户，点击下方按钮完成绑定操作'}
            type="success"
            showIcon
          />
          <Alert
            style={{
              marginBottom: 24,
            }}
            message="如您有多个单位需要关联可与管理员联系进行绑定"
            type="warning"
            showIcon
          />
        </>
      );
    }
  };

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        overflow: 'auto',
        backgroundImage:
          "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
        // backgroundImage: '/page_login_layout_bg_img_4.png',
        backgroundSize: '100% 100%',
      }}
    >
      <Helmet>
        <title>{helmetMessage()}账户 - 重庆市新闻选题管理平台</title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 360,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.png" />}
          title="重庆市新闻选题管理平台"
          subTitle={'重庆市委宣传部'}
          submitter={{
            searchConfig: {
              submitText: helmetMessage(),
            },
            submitButtonProps: {
              size: 'large',
              style: {
                width: '100%',
              },
            },
          }}
          actions={
            <Alert
              style={{
                marginTop: '25px',
              }}
              message={
                <>
                  如碰到问题可联系管理员进行咨询
                  <ContactDrawer />
                </>
              }
              type="warning"
            />
          }
          onFinish={async (values) => {
            if (bindStep === 0) {
              bindAccountQueryByPhone({ ...values }).then(({ code, msg, data }) => {
                if (data.bindState === 4) {
                  //已经绑定并且激活、启用状态的账户
                  setTimeout(() => {
                    history.push('/');
                  }, 100);
                } else if (data.bindState === 0) {
                  //无用户未绑定未激活未启动
                  loadOrganizationData();
                  setDisabledPhoneState(true);
                } else {
                  //其他状态
                  setDisabledPhoneState(true);
                }
                setBindStateState(data.bindState);
                setBindStepState(1);
              });
            } else {
              // if (!history) return;
              const search = parse(location.search);
              const { wechat } = search as { wechat: string };

              if (bindStep === 1 && bindState === 0) {
                if (values.bindOrganizations === undefined) {
                  message.error('请选择关联单位');
                  return false;
                }

                const ids = values.bindOrganizations.map((value) =>
                  value.organizationIds.toString(),
                );

                const idsSet = new Set(ids);

                if ([...idsSet].length !== ids.length) {
                  message.error('请不要重复选择相同单位');
                  return false;
                }
              }

              loginAppForWechatBindAccount({ wechat, serviceName: 'xtbs', ...values }).then(
                async ({ code, data }) => {
                  if (code === 0) {
                    if (data.state === 2 && bindStep === 1 && bindState === 0) {
                      message.success('注册成功，请等待管理员审核');
                      setTimeout(() => {
                        history.push('/user/login');
                      }, 100);
                    } else if (data.state === 2 && bindStep === 1 && bindState === 1) {
                      message.success('绑定成功，请等待管理员审核');
                      setTimeout(() => {
                        history.push('/user/login');
                      }, 100);
                    } else if (data.state === 4) {
                      setToken(data.satoken, data.loginCombineId);
                      const userInfo = await initialState?.fetchUserInfo?.();
                      if (userInfo) {
                        setInitialState({
                          ...initialState,
                          currentUser: userInfo,
                        });
                        setTimeout(() => {
                          history.push('/');
                        }, 100);
                      }
                    }
                  }
                },
              );
            }
          }}
        >
          {alertContainer()}

          <ProFormText
            fieldProps={{
              size: 'large',
              prefix: <MobileOutlined className={'prefixIcon'} />,
            }}
            name="phone"
            placeholder={'手机号'}
            disabled={disabledPhone}
            rules={[
              {
                required: true,
                message: '请输入手机号！',
              },
              {
                pattern: /^1\d{10}$/,
                message: '手机号格式错误！',
              },
            ]}
          />
          <ProFormText
            hidden={!(bindStep === 1 && bindState === 0)}
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={'prefixIcon'} />,
            }}
            name="name"
            placeholder={'姓名'}
            rules={[
              {
                required: bindStep === 1 && bindState === 0,
                message: '请输入姓名！',
              },
            ]}
          />
          {bindStep === 1 && bindState === 0 && treeOrganizationData && (
            <ProFormList
              name="bindOrganizations"
              label="关联单位"
              creatorButtonProps={{
                position: 'bottom',
                creatorButtonText: '新增',
              }}
              copyIconProps={false}
              deleteIconProps={{
                tooltipText: '不需要这行了',
              }}
            >
              <ProFormGroup key="group">
                <ProFormCascader
                  width="md"
                  fieldProps={{
                    size: 'large',
                    options: treeOrganizationData,
                    // showSearch: { filter },
                  }}
                  name="organizationIds"
                  placeholder="选择单位"
                  rules={[
                    {
                      required: bindStep === 1,
                      message: '选择单位!',
                    },
                  ]}
                />
              </ProFormGroup>
            </ProFormList>
          )}
        </LoginForm>
      </div>

      <Footer />
    </div>
  );
};
